/**
 * Copyright 2011, Wannabet Developers
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.wannabet.oauth.sign
{
	import com.googlecode.wannabet.oauth.OAuthConsumer;
	import com.googlecode.wannabet.oauth.OAuthToken;
	import com.hurlant.crypto.Crypto;
	import com.hurlant.crypto.hash.HMAC;
	import com.hurlant.util.Base64;
	import com.hurlant.util.Hex;
	
	import flash.utils.ByteArray;

	public class OAuthHMACSHA1Signer implements IOAuthSigner
	{
		public function OAuthHMACSHA1Signer() {
			super();
		}
		
		public function signRequest(signableString:String, consumer:OAuthConsumer, oauthToken:OAuthToken = null):String {
			// get the secrets to encrypt with
			var signingSecret:String = encodeURIComponent(consumer.secret) + "&"
			if (oauthToken != null && oauthToken.secret != null) {
				signingSecret += oauthToken.secret;
			}
			
			trace('signing with secret: ' + signingSecret);
			
			// hash them
			var hmac:HMAC = Crypto.getHMAC("sha1");
			var key:ByteArray = Hex.toArray(Hex.fromString(signingSecret));
			var message:ByteArray = Hex.toArray(Hex.fromString(signableString));
			
			var result:ByteArray = hmac.compute(key,message);
			var ret:String = Base64.encodeByteArray(result);
			
			return ret;
		}
	}
}
